package training.xpec;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class REWordFilter {

	/**
	 * 替换字符，用于替代原来脏话的字符,默认为"*"
	 */
	private String replacement;
	
	/**
	 * 存储文件中的词
	 */
	private List<String> wordList;
	
	public REWordFilter(File f, String repl){
		this.initWordDictFromFile(f);
		this.replacement = repl;
	}
	
	public REWordFilter(File f){
		this(f,"*");
	}
	
	
	/**
	 * 用存储于文件中的脏话初始化脏话列表
	 * @param f  存储脏话的文件
	 */
	private void initWordDictFromFile(File f){
		this.wordList = new ArrayList<String>();
		try {
			InputStream is = new FileInputStream(f);
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			try {
				String line = reader.readLine();
				//文件未读完
				while(line!=null){
					this.wordList.add(line);
					line = reader.readLine();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}
	}
	
	public String filterWithReplaceAll(String s){
		StringBuffer sb = new StringBuffer();
		for (String str : this.wordList){
			sb.append(str);
			sb.append("|");
		}
		return s.replaceAll(sb.toString(), "*");
	}
	
	public String filterWithRE(String s){
		for(String str : this.wordList){
			s = s.replaceAll(str, "*");
		}
		return s;
	}
}
